<?php
namespace Admin\Model;
use Think\Model\RelationModel;

class TeacherModel extends RelationModel {

	protected $_validate = array(
		array('id', 'require', '工号不能为空！', 1),
		array('id', 'number', '工号只能为数字！', 1),
		array('id', 'unique', '工号已存在！', 1, 'callback', 1),
		array('password', 'require', '密码不能为空！'),
		array('repassword', 'password', '输入的两次密码不一致！', 0, 'confirm'),
		array('name', 'require', '姓名不能为空！'),
		array('academy_id', 'require', '学院不能为空！'),
	);

	protected $_auto = array(
		array('id', 'intval', 3, 'function'),
		array('password', '', 2, 'ignore'),
		array('password', 'handlePassword', 3, 'callback'),
		array('academy_id', 'intval', 3, 'function'),
	);

	protected $_link = array(
		'academy' => array(
			'mapping_type'	=> self::BELONGS_TO,
			'class_name'	=> 'academy',
			'foreign_key'	=> 'academy_id',
		),
		'logic_classes'	=> array(
		    'mapping_type'  => self::HAS_MANY,
		    'class_name'    => 'LogicClass',
		    'foreign_key'   => 'teacher_id',
		),
	);

	protected function unique($id) {
		$result = $this->where(array('id' => $id))->find();
		return !$result;
	}

	protected function handlePassword($password) {
		return md5($password);
	}

	public function hasChildObj($id) {
		$result = $this->where(array('id' => $id))->relation('logic_classes')->find();
		if($result['logic_classes']) {
			$this->error = '该教师下面还有授课班级，请先删除这些逻辑班级！';
			return true;
		}
		return false;
	}

}
